using System.Runtime.InteropServices;
using Microsoft.EntityFrameworkCore;
using Universal.Application.Contracts.Common;
using Universal.Application.Contracts.Dto.Permission;
using Universal.Application.Repositories;
using Universal.Domain.Entities.App;
using Universal.Domain.Repositories;

namespace Universal.Application.Services;

/// <summary>
/// 权限服务
/// </summary>
public class PermissionService : IPermissionService
{
    private readonly IRepository<AppUser> _userRepository;
    private readonly IRepository<AppMenu> _menuRepository;
    private readonly IRepository<AppPermission> _permissionRep;
    private readonly ILogService _logService;

    public PermissionService(
        IRepository<AppUser> userRepository,
        IRepository<AppMenu> menuRepository,
        IRepository<AppPermission> permissionRep,
        ILogService logService)
    {
        _userRepository = userRepository;
        _menuRepository = menuRepository;
        _permissionRep = permissionRep;
        _logService = logService;
    }

    /// <summary>
    /// 获取用户按钮权限
    /// </summary>
    public async Task<ApiResponse<List<string>>> GetUserPermissionCodesAsync(Guid userId)
    {
        // 直接查询用户及其角色和权限
        var user = await _userRepository.Query()
            .Include(u => u.Roles)
            .ThenInclude(r => r.Permissions)
            .FirstOrDefaultAsync(u => u.Id == userId);

        if (user == null)
            return ApiResponse<List<string>>.Failure(404, "用户不存在");

        var permissionCodes = user.Roles
            .SelectMany(r => r.Permissions)
            .Select(p => p.Code)
            .Distinct()
            .ToList();

        return ApiResponse<List<string>>.Success(permissionCodes);
    }

    /// <summary>
    /// 检查用户是否有指定权限
    /// </summary>
    public async Task<bool> HasPermissionAsync(Guid userId, string permissionCode)
    {
        Console.WriteLine($"[PermissionService] 开始检查用户 {userId} 的权限 {permissionCode}");

        // 直接查询用户及其角色和权限
        var user = await _userRepository.Query()
            .Include(u => u.Roles)
            .ThenInclude(r => r.Permissions)
            .FirstOrDefaultAsync(u => u.Id == userId);

        if (user == null)
        {
            Console.WriteLine($"[PermissionService] 用户 {userId} 不存在");
            return false;
        }

        Console.WriteLine($"[PermissionService] 用户 {user.Username} 的角色数量: {user.Roles.Count}");

        var permissions = user.Roles
            .SelectMany(r => r.Permissions)
            .Select(p => p.Code)
            .Distinct()
            .ToList();

        Console.WriteLine($"[PermissionService] 用户权限列表: {string.Join(", ", permissions)}");

        var hasPermission = permissions.Contains(permissionCode);
        Console.WriteLine($"[PermissionService] 用户是否有权限 {permissionCode}: {hasPermission}");

        return hasPermission;
    }

    /// <summary>
    /// 获取所有权限列表
    /// </summary>
    public async Task<ApiResponse<PagedResult<PermissionViewDto>>> GetPermissionsPagedAsync(int pageIndex, int pageSize)
    {
        var (permissions, totalCount) = await _permissionRep.GetPagedAsync(pageIndex, pageSize);

        //转换为Dto
        var permissionsDto = permissions.Select(permission => new PermissionViewDto
        (
            permission.Id,
            permission.PermissionName,
            permission.Code,
            permission.IsActive,
            permission.CreatedAt,
            permission.UpdatedAt
        ));

        var pagedResult = new PagedResult<PermissionViewDto>
        {
            TotalCount = totalCount,
            TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize),
            PageIndex = pageIndex,
            PageSize = pageSize,
            Items = permissionsDto.ToList()
        };

        return ApiResponse<PagedResult<PermissionViewDto>>.Success(pagedResult);

    }

    /// <summary>
    /// 创建权限
    /// </summary>
    public async Task<dynamic> CreatePermissionAsync(CreatePermissionDto dto)
    {
        var Permissions = await _permissionRep.GetAllAsync();

        var PermissionCode = Permissions.FirstOrDefault(c => c.Code == dto.Code);

        if (PermissionCode != null)
        {
            return ApiResponse<string>.Failure(5001, $"权限编码{dto.Code}已存在,请重新输入");
        }

        var PermissionName = Permissions.FirstOrDefault(n => n.PermissionName == dto.PermissionName);

        if (PermissionName != null)
        {
            return ApiResponse<string>.Failure(5002, $"权限名称{dto.PermissionName}已存在,请重新输入");
        }

        var permission = new AppPermission
        {
            PermissionName = dto.PermissionName,
            Code = dto.Code,
            IsActive = dto.IsActive
        };

        var created = await _permissionRep.AddAsync(permission);
        await _logService.WriteLogAsync($"权限{dto.PermissionName}创建成功");

        return ApiResponse<string>.Success("权限创建成功");

    }

    /// <summary>
    /// 编辑权限
    /// </summary>
    public async Task<dynamic> UpdatePermissionAsync(Guid permissionId, UpdatePermissionDto dto)
    {
        var permission = await _permissionRep.GetByIdAsync(permissionId);

        if (permission == null)
        {
            return ApiResponse<string>.Failure(5001, "权限不存在");
        }

        if (permission.Code == dto.Code)
        {
            return ApiResponse<string>.Failure(5002, $"权限编码{dto.Code}已存在");
        }

        permission.PermissionName = dto.PermissionName;
        permission.Code = dto.Code;

        await _permissionRep.UpdateAsync(permission);
        await _logService.WriteLogAsync($"权限{dto.PermissionName}更新成功");
        return ApiResponse<string>.Success("权限更新成功");

    }

    /// <summary>
    /// 删除权限
    /// </summary>
    public async Task<dynamic> DeletePermissionAsync(Guid id)
    {
        var permission = await _permissionRep.GetByIdAsync(id);
        if (permission == null)
        {
            return ApiResponse<bool>.Failure(5001, "权限不存在");
        }

        await _permissionRep.DeleteAsync(permission);
        await _logService.WriteLogAsync($"权限{permission.PermissionName}删除成功");
        return ApiResponse<string>.Success("权限删除成功");
    }

    // 禁用按钮
    public async Task<dynamic> EnablePermissionAsync(Guid permissionId)
    {
        var permission = await _permissionRep.GetByIdAsync(permissionId);

        if (permission == null)
        {
            return ApiResponse<string>.Failure(5001, "权限不存在，请确认后重试!!");
        }

        if (permission.IsActive == true)
        {
            return ApiResponse<string>.Failure(5002, "权限已启用，无需多次启用!!");
        }

        permission.IsActive = true;

        await _permissionRep.UpdateAsync(permission);
        await _logService.WriteLogAsync($"权限{permission.PermissionName}启用成功");
        return ApiResponse<string>.Success("启用成功");
    }

    // 启用权限
    public async Task<dynamic> DisablePermissionAsync(Guid permissionId)
    {

        var permission = await _permissionRep.GetByIdAsync(permissionId);

        if (permission == null)
        {
            return ApiResponse<string>.Failure(5001, "权限不存在，请确认后重试!!");
        }

        if (permission.IsActive == false)
        {
            return ApiResponse<string>.Failure(5002, "权限已禁用，无需多次禁用!!");
        }

        permission.IsActive = false;

        await _permissionRep.UpdateAsync(permission);
        await _logService.WriteLogAsync($"权限{permission.PermissionName}禁用成功");
        return ApiResponse<string>.Success("禁用成功");

    }
}